<template>
  <template v-if="type == 'grid'">
    <ul class="el-upload-list el-upload-list--picture-card">
      <li :style="{width: `${size}px`, height: `${size}px`}" v-for="(file, index) in fileList" :key="index"
          class="el-upload-list__item is-success" tabindex="0">
        <el-image v-if="isImage(file.ext)" class="el-upload-list__item-thumbnail" :src="file.src" alt="">
          <template #placeholder>
            <el-image :src="`${publicPath}images/placeholder.png`"></el-image>
          </template>

        </el-image>
        <el-image v-else-if="isPdf(file.ext)" class="el-upload-list__item-thumbnail"
                  :src="`${publicPath}images/pdf.png`"
                  alt="">
          <template #placeholder>
            <el-image :src="`${publicPath}images/placeholder.png`"></el-image>
          </template>
        </el-image>
        <el-image v-else-if="isDoc(file.ext)" class="el-upload-list__item-thumbnail"
                  :src="`${publicPath}images/word.png`"
                  alt="">
          <template #placeholder>
            <el-image :src="`${publicPath}images/placeholder.png`"></el-image>
          </template>
        </el-image>
        <el-image v-else-if="isExcel(file.ext)" class="el-upload-list__item-thumbnail"
                  :src="`${publicPath}images/excel.png`" alt="">
          <template #placeholder>
            <el-image :src="`${publicPath}images/placeholder.png`"></el-image>
          </template>
        </el-image>
        <el-image v-else class="el-upload-list__item-thumbnail" :src="`${publicPath}images/file.png`" alt="">
          <template #placeholder>
            <el-image :src="`${publicPath}images/placeholder.png`"></el-image>
          </template>
        </el-image>
        <label class="el-upload-list__item-status-label">
          <i class="el-icon el-icon--upload-success el-icon--check">
            <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
              <path fill="currentColor"
                    d="M406.656 706.944 195.84 496.256a32 32 0 1 0-45.248 45.248l256 256 512-512a32 32 0 0 0-45.248-45.248L406.592 706.944z"></path>
            </svg>
          </i>
        </label>

        <span class="el-upload-list__item-actions">
            <span v-if="isImage(file.ext) || isPdf(file.ext)" class="el-upload-list__item-preview" @click="onPreview(file)">
            <el-icon><zoom-in/></el-icon>
            </span>
            <span v-if="!isImage(file.ext)" class="el-upload-list__item-delete" @click="onDownload(file)">
              <el-icon><Download/></el-icon>
            </span>
            <span v-if="!disabled" class="el-upload-list__item-delete" @click="onRemove(file, index)">
              <el-icon><Delete/></el-icon>
            </span>
          </span>
      </li>
    </ul>
  </template>
  <template v-else>
    <ul class="el-upload-list el-upload-list--text">
      <li v-for="(file, index) in fileList" :key="index" class="el-upload-list__item is-success" tabindex="0">
        <div class="el-upload-list__item-info"><a class="el-upload-list__item-name">
          <el-image v-if="isPdf(file.ext)" style="width: 16px" :src="`${publicPath}images/pdf.png`" alt=""/>
          <el-image v-else-if="isDoc(file.ext)" style="width: 16px" :src="`${publicPath}images/word.png`" alt=""/>
          <el-image v-else-if="isExcel(file.ext)" style="width: 16px" :src="`${publicPath}images/excel.png`" alt=""/>
          <i v-else class="el-icon el-icon--document">
            <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
              <path fill="currentColor"
                    d="M832 384H576V128H192v768h640V384zm-26.496-64L640 154.496V320h165.504zM160 64h480l256 256v608a32 32 0 0 1-32 32H160a32 32 0 0 1-32-32V96a32 32 0 0 1 32-32zm160 448h384v64H320v-64zm0-192h160v64H320v-64zm0 384h384v64H320v-64z"></path>
            </svg>
          </i>

          <span @click="onPreview(file)" class="el-upload-list__item-file-name">{{ file.name }}</span></a>
        </div>

        <label class="el-upload-list__item-status-label">
          <i v-if="!disabled" class="el-icon el-icon--upload-success el-icon--circle-check">
            <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
              <path fill="currentColor"
                    d="M512 896a384 384 0 1 0 0-768 384 384 0 0 0 0 768zm0 64a448 448 0 1 1 0-896 448 448 0 0 1 0 896z"></path>
              <path fill="currentColor"
                    d="M745.344 361.344a32 32 0 0 1 45.312 45.312l-288 288a32 32 0 0 1-45.312 0l-160-160a32 32 0 1 1 45.312-45.312L480 626.752l265.344-265.408z"></path>
            </svg>
          </i>
        </label>
        <i v-if="!disabled" @click="onRemove(file, index)" class="el-icon el-icon--close">
          <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
            <path fill="currentColor"
                  d="M764.288 214.592 512 466.88 259.712 214.592a31.936 31.936 0 0 0-45.12 45.12L466.752 512 214.528 764.224a31.936 31.936 0 1 0 45.12 45.184L512 557.184l252.288 252.288a31.936 31.936 0 0 0 45.12-45.12L557.12 512.064l252.288-252.352a31.936 31.936 0 1 0-45.12-45.184z"></path>
          </svg>
        </i>
      </li>
    </ul>
  </template>
</template>

<script setup name="x-file-view">
import {Download, Delete, ZoomIn} from '@element-plus/icons-vue';
import {GlobalConfig} from 'core';

let fileList = ref([]);
const {appConfig} = GlobalConfig();
let httpConfig = appConfig.http;
const emit = defineEmits(['remove'])
const props = defineProps({
  list: {
    type: [Array, Object],
    default: () => {
      return []
    }
  },

  size: {
    type: Number,
    default: 90,
  },

  type: {
    type: String,
    default: "grid"
  },

  disabled: {
    type: Boolean,
    default: true,
  },

  business: {
    type: String,
    default: "default"
  },
})

const onPreview = (file) => {
  let img = isImage(file.ext);
  // let pdf = isPdf(file.ext);
  if (! img) {
    onDownload(file);
    return;
  }

  Dialog.open("img", "预览", {
    width: '880px',
    props: {
      style: {width: '850px', textAlign: 'center'},
      src: Helper.joinUrl( httpConfig.downloadUrl , file.url)
    },
    confirmText: '',
    cancelText: ''
  })
}

const onDownload = (file) => {
  Http.download({name: file.name, business: props.business}, file.url)
}

const onRemove = (file, index) => {
  fileList.value.splice(index, 1);
  emit("remove", index, file, fileList.value);
}

const handlerValue = async (list) => {
  if (Helper.empty(list)) {
    return;
  }

  let fileListTemp = [];
  if (Array.isArray(list)) {
    for (let i = 0; i < list.length; i++) {
      let file = list[i];
      fileListTemp.push(await handlerFile(file));
    }

    fileList.value = fileListTemp;
    return;
  }

  fileList.value.push(await handlerFile(list))
}

const handlerFile = async (file) => {
  if(Helper.empty(file)) {
    return {};
  }
  //todo 处理文件扩展名
  let obj = {};
  obj.name = getFileNameByUrl(file);
  obj.ext = obj.name.substring(obj.name.lastIndexOf(".") + 1);
  obj.url = file;
  if(file.indexOf("http://") == -1 && file.indexOf("https://") == -1) {
    obj.src = httpConfig.downloadUrl + file;
  } else {
    obj.src = file;
  }

  return obj;
}

const isImage = (ext) => {
  if (Helper.empty(ext)) {
    return false;
  }

  return ['jpeg', 'png', 'git', 'jpg'].indexOf(ext) > -1;
}

const isPdf = (ext) => {
  if (Helper.empty(ext)) {
    return false;
  }

  return ['pdf'].indexOf(ext) > -1;
}

const isDoc = (ext) => {
  if (Helper.empty(ext)) {
    return false;
  }

  return ['doc', 'docx', 'wps'].indexOf(ext) > -1;
}

const isExcel = (ext) => {
  if (Helper.empty(ext)) {
    return false;
  }

  return ['xls', 'xlsx', 'xlsm'].indexOf(ext) > -1;
}

const getFileNameByUrl = (file) => {
  let fileName = "";
  if(file.indexOf("?") > -1) {
    let suffix = file.split("?")[1];
    if(! Helper.empty(suffix)) {
      let paramArr = suffix.split("&");
      for (let i=0;i<paramArr.length;i++) {
        let item = paramArr[i].split("=");
        let key = item[0];
        if((key == 'name' || key == 'fileName' )&& item.length == 2) {
          fileName = item[1];
          break
        }
      }
    }
  }

  if(Helper.empty(fileName)) {
    fileName = file.substring(file.lastIndexOf("/") + 1);
  }

  return fileName;
}

watch(() => props.list, (value) => {
  handlerValue(value);
}, {immediate: true, deep: true})

</script>

<style scoped lang="less">

:global(.el-upload-list--picture-card) {
  display: block;
  flex-wrap: wrap;
  padding: 0;
  box-sizing: border-box;
  margin-top: 6px;
  background: transparent;


  .el-image__wrapper {
    position: static;
    display: flex;
    //justify-content: center;
    //align-items: center;
  }

  .el-image__error {
    font-size: 14px;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-placeholder);
    vertical-align: middle;
  }

}

:global(.el-upload-list) {
  padding: 0;
  list-style: none;
  position: relative;
  background-color: transparent;
}
</style>
